package com.example.lib.utils;

import android.os.Environment;

import com.example.lib.LibApp;
import com.example.lib.listener.SaveListener;
import com.example.lib.utils.thread.ThreadPool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

public class FileUtils {

    public static File getNewApkFile(String name) {
        File externalFilesDir = LibApp.appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        if (!externalFilesDir.exists()) {
            externalFilesDir.mkdirs();
        }
        File newFile = new File(externalFilesDir, "/apk");
        if (!newFile.exists()) {
            newFile.mkdirs();
        }

        File apkFile = new File(newFile, name + ".apk");
        if (!newFile.exists()) {
            try {
                newFile.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return apkFile;
    }

    public static void saveText(File file, String text) {
        ThreadPool.getInstance().execute(() -> {
            FileOutputStream fileOutputStream = null;
            PrintWriter writer = null;
            try {
                boolean isExists = file.exists();
                if (!file.exists()) {
                    isExists = file.createNewFile();
                }
                if (isExists) {
                    fileOutputStream = new FileOutputStream(file);
                    writer = new PrintWriter(fileOutputStream);
                    writer.write(text);
                    writer.flush();
                }
            } catch (RuntimeException | IOException ignore) {
                ignore.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) fileOutputStream.close();
                    if (writer != null) writer.close();
                } catch (IOException ignore) {
                }
            }
        });
    }

    public static void saveInputStream(File file, InputStream stream, SaveListener listener) {
        ThreadPool.getInstance().execute(() -> {
            try {
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int byteCount;
                long sum = 0;
                while ((byteCount = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                    sum += byteCount;
                    listener.onProgress(sum);
                }
                fos.flush();
                stream.close();
                fos.close();
                listener.onSuccess(file.getAbsolutePath());
            } catch (RuntimeException | IOException e) {
                e.printStackTrace();
                listener.onFail();
            }
        });
    }
}

